﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        Socket serverSocket;
        Socket curSocket;
        int port = 0;
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket.Bind(new IPEndPoint(ip, 7100));
            serverSocket.Listen(2);
            Thread thread = new Thread(Accept);
            thread.Start();

        }
        void Accept()
        {
            while (true)//注意该循环,服务端要持续监听
            {
                curSocket = serverSocket.Accept();//接收客户端发过来的数据，并且创建了一个新的Socket实例.
                Thread thread = new Thread(Receive);
                thread.Start();
            }
        }
        void Receive()
        {
            while (true)
            {
                try
                {
                    Byte[] msg = new byte[1024];
                    if (curSocket.Receive(msg) > 0)
                    {
                        textBox1.Text = Encoding.UTF8.GetString(msg).Trim('\0', ' ');
                    }
                }
                catch
                {
                    curSocket.Close();
                    break;
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Byte[] msg = Encoding.UTF8.GetBytes(textBox2.Text);
            curSocket.Send(msg);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            f.Show();
        }

    }
}
